import React, { useState, useEffect } from 'react';
import {
  getRole,
  getMenu,
  incrementRole,
  deleteRole,
  getMenuByRoleId,
  updateRole,
} from '../../../apis';
import { Table, Button, Tag, Drawer, Form, Input, Tree } from 'antd';
import qs from 'query-string';
import { SettingOutlined, DeleteOutlined } from '@ant-design/icons';

const { TextArea } = Input;

export default function Role() {
  const [data, setData] = useState([]);
  const [auth, setAuth] = useState([]);
  const [info, setInfo] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [status, setStatus] = useState();
  const [visible, setVisible] = useState(false);

  // 树形数据
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  useEffect(() => {
    getRoleData();
    getMenuData();
  }, []);
  // 修改角色
  const update = async (values) => {
    setInfo({
      roleName: values.roleName,
      remark: values.remark,
      roleId: values.roleId,
    });
    const result = await getMenuByRoleId(values.roleId);
    setCheckedKeys(result);
    setVisible(true);
    setStatus('update');
  };
  // 删除角色
  const delRole = async (values) => {
    const result = await deleteRole(values.roleId);
    getRoleData();
  };
  // 新增角色
  const increment = () => {
    setVisible(true);
    setStatus('increment');
  };
  // 获取角色数据
  async function getRoleData() {
    const result = await getRole({ pageSize: 100 });
    result.rows.map((item) => (item.key = item.roleId));
    setData(result.rows);
  }
  async function getMenuData() {
    const result = await getMenu();
    setAuth(result.rows.children);
  }
  // tab多选框
  function onSelectChange(selectedRowKeys) {
    setSelectedRowKeys(selectedRowKeys);
  }

  // 关闭抽屉
  const onClose = () => {
    setVisible(false);
  };

  // 提交按钮
  const onFinish = async (values) => {
    if (status == 'increment') {
      values.menuId = checkedKeys;
      const result = await incrementRole(qs.stringify(values));
      getRoleData();
      setVisible(false);
    } else if (status == 'update') {
      values.menuId = checkedKeys;
      values.roleId = info.roleId;
      const result = await updateRole(qs.stringify(values));
      getRoleData();
      setVisible(false);
    }
  };

  // 树状方法

  const onExpand = (expandedKeysValue) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.

    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue) => {
    // console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      width: 120,
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
      width: 220,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
    },
    {
      title: '修改事件',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      width: 120,
    },
    {
      title: '操作',
      key: 'mobile',
      width: 120,
      render: (tags) => {
        return (
          <>
            <SettingOutlined onClick={() => update(tags)} />
            &nbsp;
            <DeleteOutlined onClick={() => delRole(tags)} />
          </>
          // <IconFont onClick={update} type={`icon-dashboard`}></IconFont>
        );
      },
    },
  ];

  return (
    <div>
      <Button type="primary" ghost onClick={increment}>
        新增
      </Button>
      <Table
        rowSelection={{
          selectedRowKeys,
          onChange: onSelectChange,
        }}
        columns={columns}
        dataSource={data}
      />
      <Drawer
        title={status == 'increment' ? '新增用户' : '修改用户'}
        placement="right"
        closable={false}
        visible={visible}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          initialValues={info}
        >
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="角色描述" name="remark">
            <TextArea />
          </Form.Item>

          <Form.Item
            label="权限选择"
            name="menuId"
            rules={[
              {
                type: 'email',
                message: '请输入正确的邮箱',
              },
            ]}
          >
            <Tree
              checkable
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              onCheck={onCheck}
              checkedKeys={checkedKeys}
              treeData={auth}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button onClick={onClose}>取消</Button>
            &nbsp;
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
